package com.wrb.customer.service;

import com.wrb.customer.exception.ServiceException;
import com.wrb.customer.feign.PointsServiceFeign;
import com.wrb.customer.mapper.CustomerMapper;
import com.wrb.customer.model.Customer;
import com.wrb.customer.model.CustomerCriteria;
import com.wrb.customer.response.ResponseCode;
import com.wrb.customer.response.ServerResponse;
import com.wrb.customer.utils.Md5Util;
import com.wrb.customer.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author wrb
 * @date 2019/11/20 17:00
 */
@Slf4j
@Service
public class CustomerService {

	@Autowired
	private CustomerMapper customerMapper;

	@Autowired
	private PointsServiceFeign pointsServiceFeign;

	/**
	 * 用户注册
	 *
	 * @param customer
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public void register(Customer customer) throws ServiceException {
		// 创建用户
		long id = SnowflakeIdWorker.generateId();
		customer.setCustomerId(id);
		String password = Md5Util.md5(customer.getPassword());
		customer.setPassword(password);
		if (this.customerMapper.insertSelective(customer) == 0){
			throw new ServiceException(ResponseCode.DB_ERROR, "用户注册失败");
		}
		// 生成积分钱包 TODO 此处可以放入队列中异步处理
		ServerResponse<Integer> response = pointsServiceFeign.addWallet(id);
		int ret = ServerResponse.parseResponse(response);
		if (ret == 0) {
			throw new ServiceException(ResponseCode.DB_ERROR, "积分钱包创建失败");
		}
	}

	/**
	 * 获取未删除用户
	 *
	 * @param id
	 * @return
	 */
	public Customer selectCustomer(long id) {
		Customer customer = this.customerMapper.selectByPrimaryKey(id);
		if (customer.getDeleteStatus()) {
			return null;
		}
		return customer;
	}

	public Customer selectByKey(long id) {
		return this.customerMapper.selectByPrimaryKey(id);
	}

	/**
	 * 判断昵称是否被占用，true 为已占用，false 为未占用
	 *
	 * @param nickname
	 * @return
	 */
	public boolean checkNickname(String nickname) {
		CustomerCriteria criteria = new CustomerCriteria();
		criteria.or().andNicknameEqualTo(nickname).andDeleteStatusEqualTo(false);
		return !CollectionUtils.isEmpty(this.customerMapper.selectByExample(criteria));
	}

	public Customer selectByNicknameAndPassword(String nickname, String password) {
		password = Md5Util.md5(password);
		CustomerCriteria criteria = new CustomerCriteria();
		criteria.or().andNicknameEqualTo(nickname).andPasswordEqualTo(password).andDeleteStatusEqualTo(false);
		List<Customer> customerList = this.customerMapper.selectByExample(criteria);
		if (CollectionUtils.isEmpty(customerList)) {
			return null;
		}
		return customerList.get(0);
	}
}
